import React from 'react'
import { Menu } from 'antd';
import type { MenuProps } from 'antd';
import { Link } from 'react-router-dom';
// 引入如有数组
import routes from '@/router/routes';
//导入方法用来处理 用户返回的菜单数组
import { getNewCheckedKeysFn, getNewRoutes } from '@/utils/common';
import { useAppSelector } from '@/store/hooks/index'
// 引入loadsh 使用该方法进行递归深拷贝
import _ from 'lodash';


type MenuItem = Required<MenuProps>['items'][number];
function getItem(
    label: React.ReactNode,
    key: React.Key,
    icon?: React.ReactNode,
    children?: MenuItem[],
    type?: 'group',
): MenuItem {
    return {
        key,
        icon,
        children,
        label,
        type,
    } as MenuItem;
}
type Props = {}

export default function Appmenu({ }: Props) {
    // copyRoutes 为深拷贝的路由routes ,所以当操作该copyRoutes进行删除操作时, 不影响原routes路由
    let copyRoutes = _.cloneDeep(routes);

    const checkedKeys = useAppSelector(state => state.userinfo.checkedkeys)
    // console.log('checkedKeys', checkedKeys);
    // console.log('newcheckedKeys', getNewCheckedKeysFn(checkedKeys));
    // console.log('newRoutes', getNewRoutes(copyRoutes, getNewCheckedKeysFn(checkedKeys)))
    // 获取当前登录的账户信息
    const adminname = useAppSelector(state => state.userinfo.adminname)

    const newRoutes = adminname == 'admin' ? routes : getNewRoutes(copyRoutes, getNewCheckedKeysFn(checkedKeys))
    //console.log('newRoutes', newRoutes);
    // 处理渲染的左侧菜单栏函数
    const getItemsFn = (newRoutes: any) => {
        let routesmenu = newRoutes.map((item: any) => {
            // 判断一级菜单
            if (item.label && item.key) {
                if (item.children) {
                    return getItem(item.label, item.key, item.icon,
                        getItemsFn(item.children) // 递归调用
                    )
                } else {
                    return getItem(<Link to={item.path}>{item.label}</Link>, item.key, item.icon)
                }

            } else {
                return null
            }
        })

        return routesmenu
    }

    return (
        <Menu
            theme="dark"
            mode="inline"
            defaultSelectedKeys={['1']}
            items={getItemsFn(newRoutes)}
        />
    )
}